from flask import Flask, abort, request, jsonify
import redis
import json
import time

# 创建redis全局变量
RedisHost='10.4.1.106'
RedisPort = '6383'
RedisStatusDB = '0'
# password='xz85742629'

RedisConnection = redis.Redis(host=RedisHost,port=RedisPort, db=RedisStatusDB)


app = Flask(__name__)
def Log(name,value=";"):
    print(name)
    print(value)
    #return print("Log:"+name+":"+value)

@app.route('/HelloWorld')
def hello_world():
    return "Hello World!"
#-----------------------------------------------------------------------------------------





def getStatusData(terminalCodeList):
    Log("getStatusData", "START");
    Log("terminalCodeList", terminalCodeList);
    ResultDict = []
    ListLen = len(terminalCodeList)
    Log("getStatusData.ListLen", ListLen);
    for index in range(ListLen):
        Log("[index]:" , index);
        Log("terminalCodeList[index]:", terminalCodeList[index]);
        VINResult = getVINStatusData(terminalCodeList[index])
        Log("len(VINResult):", len(VINResult));
        if len(VINResult)>0:
            ResultDict.append(VINResult)

    return ResultDict

def getVINStatusData(terminalCode):
    Log("getVINStatusData", "START");
    HashGetName = "tm30_status_ehs3_VIN_pcol_realtime"
    StatusName = "tm30_status_ehs3_vin_value_cache"
    #HashGetKey = "LFPHC7PE1K1A06216"
    #HashGetKey = terminalCodeList[0]
    #Log(HashGetName, HashGetKey);
    #print(RedisConnection.hget("tm30_status_ehs3_VIN_pcol_realtime", "LFPHC7PE6K1A13713"))
    # print(RedisConnection.hget(HashGetName, HashGetKey))
    #global StatusName
    Log("getVINStatusData.StatusName", StatusName);
    redisResult = RedisConnection.hget(StatusName, terminalCode)

    if redisResult == None:
        Log('redisResult', 'is None');
    else:
        Log('redisResult', 'is OK');
        Log("redisResult", redisResult);
        redisResultDecode = redisResult.decode('utf-8')
        redisResultClean = redisResultDecode.replace(' u\'', ' \'')
        redisResultClean = redisResultClean.replace('{u\'', '{\'')
        redisResultClean = redisResultClean.replace('\'', '\"')
        Log("redisResultClean", redisResultClean);

        # redisResultDecodeLoads = json.loads(redisResultDecode)

        # print(redisResultDecodeLoads);
        print(type(redisResultClean))
        global redisResultJSON
        redisResultJSON = json.loads(redisResultClean)
    # redisResultJSON = json.dumps(redisResultClean)
    #print(type(redisResultJSON))
    # print(type(jsObj))
    Log("redisResultJSON", redisResultJSON);
    # for city in js['cityJsonArray']:
    # print
    # city['cityId']

    eventCode = redisResultJSON['event_code']
    Log("eventCode", eventCode);
    terminalCode = redisResultJSON['vin']
    Log("terminalCode", terminalCode);
    lat = redisResultJSON['data']['GPS003']['val']  # GPS003	纬度
    Log("lat", lat);
    lgt = redisResultJSON['data']['GPS002']['val']  # GPS002	经度
    Log("lgt", lgt);
    angle = redisResultJSON['data']['GPS006']['val']  # GPS006	方向
    Log("angle", angle);
    speed = redisResultJSON['data']['V019']['val']  # V019	整车车速
    Log("speed", speed);
    totalKm = redisResultJSON['data']['V015']['val']  # V015	总里程
    Log("totalKm", totalKm);
    enableKm = redisResultJSON['data']['V133']['val']  # V133	续航剩余里程
    Log("enableKm", enableKm);
    lastRefreshTime = redisResultJSON['data']['GPS007']['val']  # GPS007	GPS时间
    Log("lastRefreshTime", lastRefreshTime);
    soc = redisResultJSON['data']['E010']['val']  # E010	电池电量（SOC）
    Log("soc", soc);

    ResultVINDict = {}
    ResultVINDict['eventCode'] = eventCode
    ResultVINDict['terminalCode'] = terminalCode
    ResultVINDict['lat'] = lat
    ResultVINDict['lgt'] = lgt
    ResultVINDict['angle'] = angle
    ResultVINDict['speed'] = speed
    ResultVINDict['totalKm'] = totalKm
    ResultVINDict['enableKm'] = enableKm
    ResultVINDict['lastRefreshTime'] = lastRefreshTime
    ResultVINDict['soc'] = soc

    return ResultVINDict

@app.route('/redis/queryVehicleInfoByTerminalCode', methods=['POST'])
# in parameter ：{"terminalCode":"LFPHC7PE0K1A06501"}
def queryVehicleInfoByTerminalCode():
    time_queryVehicleInfoByTerminalCode_start=time.time()

    if not request.json or 'terminalCode' not in request.json:
        abort(400)

    terminalCode = request.json['terminalCode']
    Log("terminalCode", terminalCode);
    terminalCodeList = terminalCode.split(",")
    Log("terminalCodeList",terminalCodeList);
    ResultDict = getStatusData(terminalCodeList)
    #tasks.append(task)

    time_queryVehicleInfoByTerminalCode_end = time.time()
    print('queryVehicleInfoByTerminalCode time cost', time_queryVehicleInfoByTerminalCode_end - time_queryVehicleInfoByTerminalCode_start, 's')
    return jsonify({'code': '200','message': '成功','object': ResultDict})
    #return "queryVehicleInfoByTerminalCode!"


# 测试数据暂时存放
tasks = []

@app.route('/add_task/', methods=['POST'])
def add_task():
    if not request.json or 'id' not in request.json or 'info' not in request.json:
        abort(400)
    task = {
        'id': request.json['id'],
        'info': request.json['info']
    }
    tasks.append(task)
    return jsonify({'result': 'success'})


@app.route('/get_task/', methods=['GET'])
def get_task():
    if not request.args or 'id' not in request.args:
        # 没有指定id则返回全部
        return jsonify(tasks)
    else:
        task_id = request.args['id']
        task = filter(lambda t: t['id'] == int(task_id), tasks)
        return jsonify(task) if task else jsonify({'result': 'not found'})

if __name__=="__main__":
    #app.run(debug=True)
    app.run(host='0.0.0.0', port=6390, debug=True)